package net.xiangcaowuyu.springcloud.alibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import net.xiangcaowuyu.springcloud.alibaba.handler.MyHandler;
import net.xiangcaowuyu.springcloud.entites.CommonResult;
import net.xiangcaowuyu.springcloud.entites.Payment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * 博客：https://www.xiangcaowuyu.net
 * Description:
 *
 * @Author: 香草物语
 * DateTime: 2021-07-25 17:52
 */
@RestController
public class RateLimitController {

    @GetMapping("/fallbackOnly")
    @SentinelResource(value = "fallbackOnly", fallback = "handlefallbackOnlyException")
    public CommonResult fallbackOnly() {
        return new CommonResult(200, "按资源名称限量ok", new Payment(2020L, "SERIAL001"));
    }

    public CommonResult handlefallbackOnlyException(Throwable exception) {
        return new CommonResult(444, exception.getClass().getCanonicalName() + "\t 服务不可用");
    }

    @GetMapping("/blockHandlerOnly")
    @SentinelResource(value = "blockHandlerOnly", blockHandler = "handleblockHandlerException")
    public CommonResult blockHandlerOnly() {
        int age = 10 / 0;
        return new CommonResult(200, "按资源名称限量ok", new Payment(2020L, "SERIAL001"));
    }

    public CommonResult handleblockHandlerException(BlockException exception) {
        return new CommonResult(444, exception.getClass().getCanonicalName() + "\t 服务不可用");
    }

    @GetMapping("/byResource")
    @SentinelResource(value = "byResource", blockHandler = "handleException", fallback = "handleFallback")
    public CommonResult byResource() {
        return new CommonResult(200, "按资源名称限量ok", new Payment(2020L, "SERIAL001"));
    }

    public CommonResult handleException(BlockException exception) {
        return new CommonResult(444, "handleException\t 服务不可用");
    }

    public CommonResult handleFallback(Throwable exception) {
        return new CommonResult(444, "handleFallback\t 服务不可用");
    }

    @GetMapping("/rateLimit/customerBlockHandler")
    @SentinelResource(value = "customerBlockHandler", blockHandlerClass = MyHandler.class, blockHandler = "handlerException2")
    public CommonResult customerBlockHandler() {
        return new CommonResult(200, "按资源名称限量ok", new Payment(2020L, "SERIAL001"));
    }
}
